package com.xyzwps.ewa.modules.user

import com.xyzwps.ewa.common.Page
import com.xyzwps.ewa.modules.auth.auth
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.jetbrains.exposed.sql.transactions.transaction

fun Route.userRoutes() {
    auth {
        // Create user
        post {
            val user = call.receive<UserInfoForCreating>()
            call.respond(HttpStatusCode.Created, transaction {
                UserService.create(user)
            })
        }

        get {
            val page = Page.from(call.request)
            val pager = transaction {
                UserService.read(page)
            }
            call.respond(HttpStatusCode.OK, pager)
        }

        // Read user
        get("/{id}") {
            val id = UserId(call.parameters["id"]?.toLong() ?: throw IllegalArgumentException("Invalid ID"))
            val user = transaction { UserService.read(id) }
            if (user != null) {
                call.respond(HttpStatusCode.OK, user)
            } else {
                call.respond(HttpStatusCode.NotFound)
            }
        }

        // Update user
        put("/{id}") {
            val id = UserId(call.parameters["id"]?.toLong() ?: throw IllegalArgumentException("Invalid ID"))
            val user = call.receive<UserInfoForUpdating>()
            val newUser = transaction { UserService.update(id, user) }
            if (newUser == null) {
                call.respond(HttpStatusCode.NotFound)
            } else {
                call.respond(HttpStatusCode.OK, newUser)
            }
        }

        // Delete user
        delete("/{id}") {
            val id = UserId(call.parameters["id"]?.toLong() ?: throw IllegalArgumentException("Invalid ID"))
            transaction {
                UserService.delete(id)
            }
            call.respond(HttpStatusCode.NoContent)
        }
    }
}
